package com.step.scene.light;

import java.util.ArrayList;
import java.util.HashMap;

public class LightList {
	public static final int MAX_LIGHT_NUM = 8;
	private ArrayList<Light> lights;
	// 灯光对象与GL_LIGHT索引对应
	private HashMap<Light, Integer> lightToGlIndex;
	// 可用的灯光索引
	private ArrayList<Integer> availGlIndices;
	// 已经打开的灯光索引
	private boolean[] enabledIndices;
	
	public LightList(){
		reset();
	}
	
	/**
	 * 重置灯光设置
	 */
	public void reset(){
		if(lights == null) {
			lights = new ArrayList<Light>();
		}
		else{
			lights.clear();
		}
		
		if(lightToGlIndex == null){
			lightToGlIndex = new HashMap<Light, Integer>();
		}
		else{
			lightToGlIndex.clear();
		}
		
		if(enabledIndices == null){			
			enabledIndices = new boolean[MAX_LIGHT_NUM];
		}
		
		if(availGlIndices == null){
			availGlIndices = new ArrayList<Integer>();
		}
		else{
			availGlIndices.clear();
		}
		
		for(int i = 0; i < MAX_LIGHT_NUM; i++){
			availGlIndices.add(i);
			enabledIndices[i]=false;
		}
	}
	
	public boolean add(Light light){
		if(lights.contains(light)) return false;
		
		if(lights.size() > MAX_LIGHT_NUM) throw new Error("Light:超过最大灯光数！");
		
		boolean result = lights.add(light);
		
		if(!result) return false;
		
		int glIndex = availGlIndices.remove(0);
		lightToGlIndex.put(light, glIndex);
		enabledIndices[glIndex] = true;
		
		return result;
	}
	
	public void remove(Light light){
		boolean result = lights.remove(light);
		
		if(!result) return;
		int glIndex = lightToGlIndex.get(light);
		availGlIndices.add(glIndex);
		enabledIndices[glIndex] = false;
	}
	
	public void clear(){
		reset();
	}
	
	public int size(){
		return lights.size();
	}
	
	public Light get(int index){
		return lights.get(index);
	}
	
	public Light[] toArray(){
		return (Light[])lights.toArray(new Light[lights.size()]);
	}
	
	public int getGLIndex(Light light){
		return lightToGlIndex.get(light);
	}
	
	public Light getLight(int glIndex){
		int len = lights.size();
		
		for (int i = 0; i < len; i++) {
			Light light = lights.get(i);
			if(lightToGlIndex.get(light) == glIndex){
				return light;
			}
		}
		
		return null;
	}
	
	public boolean[] getEnabledIndices(){
		return enabledIndices;
	}
}
